package logic

import (
	"box-mart-api/cache"
	"box-mart-api/moder"
	"context"
	"encoding/json"
	"time"

	"box-mart-api/boxrpc/boxrpc"
	"box-mart-api/boxrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsListLogic) GoodsList(in *boxrpc.GoodsListRequest) (*boxrpc.GoodsListResponse, error) {
	// todo: add your logic here and delete this line

	var goods []moder.Goods
	result, _ := cache.Rdb.Get(l.ctx, "goodsList").Result()
	if result == "" {
		moder.DB.Debug().Scopes(moder.Paginate(int(in.Page), int(in.Size))).Find(&goods)
		marshal, _ := json.Marshal(goods)
		cache.Rdb.Set(l.ctx, "goodsList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &goods)
	}

	var goodslist []*boxrpc.GoodsList

	for _, good := range goods {
		list := boxrpc.GoodsList{
			Title: good.Title,
			Price: good.Price,
		}
		goodslist = append(goodslist, &list)
	}

	return &boxrpc.GoodsListResponse{
		List: goodslist,
	}, nil
}
